import {ActionTree} from 'vuex';
import {login, logout} from '@/api/login';
import {getLoginUserInfo} from '@/api/user';
import storeUtils from '@/utils/storeUtils';

const actions: ActionTree<any, any> = {
    async setRouters({state, commit}, routers: any) {
        commit('SET_ROUTERS', routers);
    },
    setToken({state, commit}, token: any) {
        commit('SET_TOKEN', token);
    },
    // 登录
    Login({commit}, userInfo: any) {
        const userName = userInfo.userName.trim();
        const password = userInfo.password;
        const code = userInfo.code;
        const key = userInfo.key;
        const rememberMe = userInfo.rememberMe;
        return new Promise((resolve, reject) => {
            login(userName, password, code, key, rememberMe).then((res: any) => {
                resolve(res);
            }).catch((error: any) => {
                reject(error);
            });
        });
    },
    // 获取用户信息
    GetInfo({commit, state}) {
        return new Promise((resolve, reject) => {
            getLoginUserInfo().then((response: any) => {
                if (response && response.data) {
                    commit('SET_ROUTERS', response.data.menu);
                    commit('SET_PERMISSION', response.data.permission);
                    commit('SET_LOGIN_USER_INFO', response.data.user);
                    if (response.data.user) {
                        commit('SET_NAME', response.data.user.name);
                        commit('SET_AVATAR', response.data.user.avatar);
                    }
                } else {
                    reject('getLoginUserInfo: data must be a non-null array !');
                }
                resolve(response);
            }).catch(error => {
                reject(error);
            });
        });
    },

    async setUserInfo({commit}, userInfo: any) {
        commit('SET_LOGIN_USER_INFO', userInfo);
    },

    // 前端 登出
    FedLogOut({commit}) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '');
            storeUtils.clearStore();
            resolve();
        });
    },
    // 退出系统
    LogOut({commit, state}) {
        return new Promise((resolve, reject) => {
            logout().then(() => {
                commit('SET_TOKEN', '');
                commit('SET_LOGIN_USER_INFO', '');
                commit('SET_PERMISSION', []);
                commit('SET_ROUTERS', []);
                storeUtils.clearStore();
                resolve();
            }).catch((error: string) => {
                reject(error);
            });
        });
    },
};

export default actions;
